package com.siblings.loan.ui.permission.impl

import android.Manifest
import android.content.Context
import android.graphics.Color
import android.view.View
import com.lib.base.utils.log.LogHelper
import com.siblings.lib_permission.XXPermissions
import com.siblings.loan.R
import com.siblings.loan.app.Apps
import com.siblings.loan.http.HttpHelper
import com.siblings.loan.ui.permission.view.ISibPermissionView
import com.siblings.loan.utils.PermissionListener
import com.siblings.loan.utils.PermissionUtils
import com.siblings.loan.utils.dialog.TipsDialog
import com.siblings.loan.utils.event.SibEventType
import com.siblings.loan.utils.helper.SharedHelper
import com.siblings.mvp.presenter.MvpPresenter
import org.json.JSONArray
import org.json.JSONObject

/**
 * SiblingsLoan
 * @Author wwdeng
 * @CreateTime: 2024/7/5 13:42
 * @Annotation：权限申请
 */
class SibPermissionPresenterImpl(context: Context?) : MvpPresenter<ISibPermissionView>(context) {

    private var permissionList: ArrayList<JSONObject>? = null
    //当前权限下标
    private var curtIndex = 0

    /**
     * 获取权限列表
     */
    fun loadSibPermissionListAction(){
        permissionList = arrayListOf<JSONObject>()
        val commonInfo = SharedHelper.getSibSPString(SharedHelper.SIB_SPKEY.SIBLINGS_COMMON)
        val obj = JSONObject(commonInfo)
        val customizeObj = obj.optJSONObject("customize")
        val permissionsObj = customizeObj?.optJSONObject("permissions")
        val permissionArray = permissionsObj?.optJSONArray("permission")
        //手动添加一条
        permissionArray!!.put(Apps.context.getString(R.string.permission_app_list_title))
        for (i in 0..<permissionArray.length()){
            val permission = permissionArray.optString(i)
            permissionList!!.add(formatSibPermissionItem(permission))
        }
        mvpView.showSibPermissionList(permissionList!!)

        curtIndex = getSibPermissionIndex()
        setSibPermission()
    }

    /**
     * 下一个
     */
    fun onSibNextAction(){
        //全部同意
        if (isAgreeAll()){
            mvpView.showSibLoginPage()
            return
        }
        //全部完成（拒绝+同意） -> 展示拒绝的权限
        if (curtIndex == permissionList!!.size){
            mvpView.showSibPermissionPage(getSibPermissionIndex())
            return
        }
        curtIndex++
        mvpView.showSibPermissionPage(curtIndex)
    }

    /**
     * 拒绝权限
     */
    fun onSibDenyClick(){
        val item = permissionList!![curtIndex]
        item.put("isDeny",true)
        if (!item.optBoolean("isMust")){//非必须权限，需要设置为已点击状态
            item.put("isClick",true)
        }
        mvpView.showSibPermissionBanned()
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_DENY,item.optString("permission"))

        onSibCheckPageClick(getSibPermissionIndex())
    }

    /**
     * 同意
     */
    fun onSibAgreeClick(){
        val item = permissionList!![curtIndex]
        val confirmDialog = TipsDialog(mvpView.getSibActivity(),item.optString("permission"),object : TipsDialog.IDialogCallback{
            override fun onClick(view: View?) {
                when(view!!.id){
                    R.id.btnOk -> {
                        hasRequestPermissions(item)
                        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_DIALOG_TIPS_OK,item.optString("permission"))
                    }
                    R.id.btnCancel -> {
                        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_DIALOG_TIPS_CANCEL,item.optString("permission"))
                    }
                }
            }
        })
        confirmDialog.setCancelable(true)
        confirmDialog.setCanceledOnTouchOutside(false)
        confirmDialog.show()
        confirmDialog.setTipsTitle(mvpView.getSibActivity().getString(R.string.tips_kind))
        confirmDialog.setTips(mvpView.getSibActivity().getString(R.string.permission_agree_tips))

        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_AGREE,item.optString("permission"))
    }

    /**
     * 切换Page
     */
    fun onSibCheckPageClick(index: Int){
        curtIndex = index
        setSibPermission()
    }

    /**
     * 已拒绝按钮
     */
    fun onSibBannedClick(){
        val item = permissionList!![curtIndex]
        XXPermissions.startPermissionActivity(mvpView.getSibActivity(),item.optString("permission"))
        HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_BANNED,item.optString("permission"))
    }

    /**
     * onResume
     */
    fun onSibPermissionResume(){
        curtIndex = getSibPermissionIndex()
        setSibPermission()
    }

    /**
     * 显示权限
     */
    private fun setSibPermission(){
        //全部允许
        if (isAgreeAll()){
            mvpView.showSibLoginPage()
            return
        }
        val item = permissionList!![curtIndex]
        mvpView.showSibPermissionPage(curtIndex)

        //必须要申请的权限  APP LIST 只做展示
        if (item.optBoolean("isMust")){
            //是否已获得权限
            val isGranted = PermissionUtils.isAuthorized(mvpView.getSibActivity(),item.optString("permission"))
            //已获得权限
            if (isGranted){
                mvpView.showSibPermissionAuthorized()
                return
            }
            //权限状态：0获取权限成功  1申请权限拒绝, 但是下次申请权限还会弹窗  2申请权限拒绝，并且是永久，不会再弹窗  3默认未请求授权状态
            val authorizeStaus = PermissionUtils.getAuthorizeStaus(mvpView.getSibActivity(),item.optString("permission"))
            //2申请权限拒绝，并且是永久，不会再弹窗 || 本次已拒绝
            if (authorizeStaus == 2 || item.optBoolean("isDeny",false)){
                mvpView.showSibPermissionBanned()
                return
            }
            mvpView.showSibPermissionNotObtained()
        } else {//非必须要申请的权限，根据isDeny 或 isAgree 显示状态
            if (item.optBoolean("isDeny")){
                mvpView.showSibPermissionBanned()
                return
            }
            if (item.optBoolean("isAgree")){
                mvpView.showSibPermissionAuthorized()
                return
            }
            mvpView.showSibPermissionNotObtained()
        }
    }

    /**
     * 是否全部已授权
     */
    private fun isAgreeAll(): Boolean{
        var isAll = true
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(context,item.optString("permission"))){
                        isAll = false
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        isAll = false
                        break
                    }
                }
            }
        }
        return isAll
    }

    /**
     * 获取未授权的权限下标
     */
    private fun getSibPermissionIndex(): Int{
        var index = curtIndex
        if (permissionList!!.size > 0){
            for (i in 0..<permissionList!!.size){
                val item = permissionList!![i]
                //必须要申请的权限，需要判断申请状态
                if (item.optBoolean("isMust")){
                    if (!XXPermissions.isGranted(mvpView.getSibActivity(),item.optString("permission")) && !item.optBoolean("isDeny",false)){
                        index = i
                        break
                    }
                } else {//非必须权限，只需要判断点击状态
                    if (!item.optBoolean("isClick")){
                        index = i
                        break
                    }
                }
            }
        }
        return index
    }

    /**
     * 获取所有权限列表
     */
    fun getSibPermissionList(): ArrayList<JSONObject>{
        return permissionList!!
    }

    /**
     * 申请权限
     */
    fun hasRequestPermissions(item: JSONObject){
        //非必须申请的权限
        if (!item.optBoolean("isMust")){
            item.put("isAgree",true)
            item.put("isClick",true)
            mvpView.showSibPermissionAuthorized()
            //验证是否全部已同意
            if (isAgreeAll()){
                mvpView.showSibLoginPage()
            } else {
                //最后一个
                if (curtIndex == permissionList!!.size - 1){
                    curtIndex = getSibPermissionIndex()
                } else {
                    curtIndex++
                }
                setSibPermission()
            }
            return
        }
        val permission = item.optString("permission")
        PermissionUtils.requestPermission(mvpView.getSibActivity(),permission,object : PermissionListener {
            override fun requestResult(isFlog: Boolean) {
                LogHelper.e("requestResult>>>>>>>>>>>>>>$isFlog")
                if (isFlog){
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_SYSTEM_AGREE,permission)
                    mvpView.showSibPermissionAuthorized()
                    //验证是否全部已同意
                    if (isAgreeAll()){
                        mvpView.showSibLoginPage()
                        return
                    }
                } else {
                    HttpHelper.addSibEventAction(SibEventType.CLICK.SIB_CLICK_PERMISSION_SYSTEM_DENY,permission)
                    mvpView.showSibPermissionBanned()
                    //最后一个
//                    if (mPermissionIndex == mPermissionList.size - 1){
//                        mPermissionIndex = getPermissionIndex()
//                    } else {
//                        mPermissionIndex++
//                    }
                }
                curtIndex = getSibPermissionIndex()
                setSibPermission()
            }
        })
    }

    /**
     * 拼装权限Item
     */
    private fun formatSibPermissionItem(permission: String): JSONObject{
        var item = JSONObject()
        item.put("permission",permission)
        item.put("isDeny",false)
        item.put("isMust",true)
        when(permission){
            Manifest.permission.READ_SMS -> {
                item.put("icon",R.mipmap.pic_permission_sms)
                item.put("title",Apps.context.getString(R.string.permission_sms_title))
                item.put("titleColor", Color.parseColor("#FF4DB673"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",Apps.context.getString(R.string.permission_sms_title))
                obj1.put("des",Apps.context.getString(R.string.permission_sms_des1))
                msgArray.put(obj1)

                val obj2 = JSONObject()
                obj2.put("title",Apps.context.getString(R.string.permission_sms_title))
                obj2.put("des",Apps.context.getString(R.string.permission_sms_des2))
                msgArray.put(obj2)

                val obj3 = JSONObject()
                obj3.put("title",Apps.context.getString(R.string.permission_sms_title))
                obj3.put("des",Apps.context.getString(R.string.permission_sms_des3))
                msgArray.put(obj3)
                item.put("msgList",msgArray)
            }
            Manifest.permission.READ_PHONE_STATE -> {
                item.put("icon",R.mipmap.pic_permission_phonestatus)
                item.put("title",Apps.context.getString(R.string.permission_phone_state_title))
                item.put("titleColor", Color.parseColor("#FFFD558C"))

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",Apps.context.getString(R.string.permission_phone_state_title))
                obj1.put("des",Apps.context.getString(R.string.permission_phone_state_des1))
                msgArray.put(obj1)
                item.put("msgList",msgArray)
            }
            Apps.context.getString(R.string.permission_app_list_title) -> {
                item.put("icon",R.mipmap.pic_permission_app_list)
                item.put("title",Apps.context.getString(R.string.permission_app_list_title))
                item.put("titleColor", Color.parseColor("#FF389EFC"))
                item.put("isAgree",false)
                item.put("isMust",false)
                item.put("isClick",false)//是否点击 拒绝 || 同意

                val msgArray = JSONArray()
                val obj1 = JSONObject()
                obj1.put("title",Apps.context.getString(R.string.permission_app_list_title))
                obj1.put("des",Apps.context.getString(R.string.permission_app_list_des1))
                msgArray.put(obj1)

                val obj2 = JSONObject()
                obj2.put("title",Apps.context.getString(R.string.permission_app_list_title))
                obj2.put("des",Apps.context.getString(R.string.permission_app_list_des2))
                msgArray.put(obj2)

                val obj3 = JSONObject()
                obj3.put("title",Apps.context.getString(R.string.permission_app_list_title))
                obj3.put("des",Apps.context.getString(R.string.permission_app_list_des3))
                msgArray.put(obj3)

                val obj4 = JSONObject()
                obj4.put("title",Apps.context.getString(R.string.permission_app_list_title))
                obj4.put("des",Apps.context.getString(R.string.permission_app_list_des4))
                msgArray.put(obj4)

                item.put("msgList",msgArray)
            }
        }
        return item
    }
}